import threading
import time


class ThreadManager:
    def __init__(self):
        self.threads = []
        self.stop_event = threading.Event()

    def start_thread(self, target, args=()):
        thread = threading.Thread(target=self._thread_wrapper, args=(target, args))
        thread.start()
        self.threads.append(thread)

    def _thread_wrapper(self, target, args):
        # 线程运行的函数会检查 stop_event 以决定是否退出
        target(*args)

    def stop_all_threads(self):
        # 设置停止事件，通知所有线程退出
        self.stop_event.set()
        # 等待所有线程结束
        for thread in self.threads:
            thread.join()

    def clear_threads(self):
        # 清理线程列表
        self.threads.clear()

    def get_stop_event(self):
        return self.stop_event


# 线程要执行的函数
def worker(stop_event):
    while not stop_event.is_set():
        print("Worker is running...")
        time.sleep(10)
    print("Worker is stopping...")


manager = ThreadManager()
# 使用 ThreadManager 管理线程
if __name__ == "__main__":
    manager = ThreadManager()

    # 创建并启动线程
    for _ in range(5):
        manager.start_thread(worker, args=(manager.get_stop_event(),))

    # 主程序的其他操作
    time.sleep(1)  # 主程序工作一段时间

    # 停止所有线程并清理
    manager.stop_all_threads()
    manager.clear_threads()

    print("Main program is exiting...")
